import { Row, Col, Popover, Avatar, Button } from 'antd'
import { AppContext } from '@/store'
import { useContext } from 'react'
import { CreateNewChat } from "@/apis"
import addIcon from '@/assets/chat_add_regular.png'
import userAvatar from "@/assets/user_avatar.png"

const Header = () => {
  const { state, dispatch } = useContext(AppContext)

  const loginOut = () => {
    dispatch({ type: 'SET_TOKEN', payload: null })
    dispatch({ type: 'SET_USER', payload: null })
    localStorage.setItem('token', '')
    localStorage.removeItem('user')
    // localStorage.removeItem('messageList')
    window.location.href = '/'
  }

  const createHandle = async() =>{
    const chat = await CreateNewChat()
    if (chat.success) {
      // 清空会话
      dispatch({type:"SET_MESSAGE_LIST", payload:[]})
      localStorage.removeItem("messageList")
    }else if(chat.code === 401){
      localStorage.removeItem("token")
      localStorage.removeItem("user")
      dispatch({ type: 'SET_VISIBLE', payload: true })
    }
   
  }
  const loginHandle =()=>{
    dispatch({type:"SET_VISIBLE",payload: true })
  }

  const loginContent = (
    <Row className="login-content">
      <Col className="username btn">{state.user?.username}</Col>
      <Col className="login-out btn" onClick={loginOut}>
        退出登录
      </Col>
    </Row>
  )

  return (
    <Row>
      <Col span={24} className="header-user btn">
        {state.pathname == '/chat' ? (
          <Col className="create-chat" onClick={createHandle}>
            <img src={addIcon} alt="" />
            <span>新增会话</span>
          </Col>
        ) : null}
        <Col span={20} className="" style={{display:'flex', justifyContent:'flex-end',marginRight:'30px'}}>
          <Popover
            placement="bottom"
            content={state.user ? loginContent : null}
            trigger="click"
          >
            {state.user ?<> <Avatar src={userAvatar}></Avatar> <span>{state.user.username}</span></>: <Button style={{fontSize:'12px'}} shape="circle"  onClick={loginHandle}>登录</Button>}
          </Popover>
        </Col>
      </Col>
    </Row>
  )
}

export default Header
